<template>
  <a-modal
    :title='edit ? "完成操作" : "附件预览"'
    :width='640'
    :visible='visible'
    :confirmLoading='loading'
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
    v-bind='edit ? {} : {footer: null}'
  >
    <a-spin :spinning='loading'>
      <a-form :form='form' v-bind='formLayout'>
        <a-form-item label='图片'>
          <a-upload
            name='file'
            :disabled='!edit'
            list-type='picture-card'
            class='avatar-uploader'
            :show-upload-list='false'
            v-decorator="['attachementFileName',
            {
              valuePropName: 'attachementFileName',
              getValueFromEvent: normFile,
              rules: [
                {
                  required: true, message: '请选择图片上传'
                }
              ]
            }]"
            :action='uploadPath'
            :headers='computedHeaders'
            :before-upload='beforeUpload'
            @change='handleChange'
            @reject='handleReject'
          >
            <img class='avatar' v-if='imageUrl' :src='imageUrl' alt='avatar' />
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class='ant-upload-text'>
                上传缺陷图片
              </div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import workerOrderApi, { downloadAvatar, getWorkorderDetail } from '@/api/workerOrder'
import { findDataDicInfoByType } from '@/api/dataDicInfo'
import { findBypageEquipment } from '@/api/equipmentManagement'
import { mapState } from 'vuex'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import moment from 'moment'

let baseUrl = window.PROJECT_CONFIG.VUE_APP_API_BASE_URL
// 表单字段
const fields = ['typeDicId', 'stationDicId', 'deviceId', 'expectedCompletionTime', 'attachementFileName', 'description', 'file']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    edit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      }
    }
    return {
      activeKey: '0',
      imageUrl: '',
      workerOrderApi,
      uploadPath: baseUrl + workerOrderApi.uploadWorkOrderPhoto,
      form: this.$form.createForm(this),
      workOrderTypeList: [],
      equipmentList: [],
      workOrderLogs: [],
      stationList: [],
      uploadLoading: false
    }
  },
  created() {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    this.getTypeList()
    this.getStationList()
    this.findBypageEquipment()
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
      this.getWorkorderDetail()
      if (this.form.getFieldValue('attachementFileName')) {
        const attachementFileName = this.form.getFieldValue('attachementFileName')
        this.imageUrl = downloadAvatar({ fileName: attachementFileName })
      } else {
        this.imageUrl = ''
      }
    })
  },
  mounted() {
  },
  watch: {
    visible(val) {
      if (val) {
        this.imageUrl = ''
      }
    }
  },
  computed: {
    ...mapState({
      token: state => state.user.token
    }),
    computedHeaders() {
      return {
        [ACCESS_TOKEN]: `Bearer ${this.token}`
      }
    }
  },
  methods: {
    moment,
    getWorkorderDetail() {
      getWorkorderDetail({
        workOrderId: this.model.id
      }).then(res => {
        this.workOrderLogs = res.workOrderLogs
      })
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if(!info.file.response.result){
        this.$message.error(info.file.response.message)
        return
      }
      if (info.file.status === 'done') {
        this.imageUrl = downloadAvatar({ fileName: info.file.response.result })
        this.uploadLoading = false
      }
    },
    handleReject(){
      this.$message.error('文件上传失败!')
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/JEPG'
      if (!isJpgOrPng) {
        this.$message.error('仅支持JPEG格式以及PNG格式文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('图片大小不得超过 10MB!')
      }
      return isJpgOrPng && isLt2M
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e
      }
      if (e.fileList && e.fileList.length) {
        return e && e.fileList && e.fileList[0].response && e.fileList[0].response.result
      }
      return ''
    },
    // 类型list
    getTypeList() {
      findDataDicInfoByType(12).then(res => {
        console.log(res)
        this.workOrderTypeList = res.map(item => {
          return {
            ...item,
            key: +item.id,
            label: item.name
          }
        })
      })
    },
    // 站点list
    getStationList() {
      findDataDicInfoByType(13).then(res => {
        console.log(res)
        this.stationList = res.map(item => {
          return {
            ...item,
            key: +item.id,
            label: item.name
          }
        })
      })
    },
    findBypageEquipment() {
      findBypageEquipment({
        pageNo: 1,
        pageSize: 999
      }).then(res => {
        this.equipmentList = res.list.map(item => {
          return {
            ...item,
            label: item.equipmentName,
            key: +item.id
          }
        })
      })
    }
  }
}
</script>

<style lang='less' scoped>

.avatar {
  width: 200px;
  height: 200px;
}
</style>

